/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useRef, useEffect } from 'react';
import { connect } from 'dva';
import { useInterval, useUpdateEffect } from 'ahooks';
import { Chart, Geom, Axis, Tooltip, Coord, Legend, Guide } from 'bizcharts';
import DataSet from '@antv/data-set';
import CommonBorder from '../../Wrappers/CommonBorder';
import NoDate from '../../Wrappers/NoDate';
import { gradualTextColumn } from '../../_utils';
import styles from '../../../commonChart.less';

const { DataView } = DataSet;

const cols = {
  num: {
    alias: '数量',
    type: 'linear',
    min: 0,
  },
};

// const brandSort = [
//   '邮政',
//   'EMS',
//   '中通',
//   '申通',
//   '圆通',
//   '韵达',
//   '百世',
//   '京东',
//   '极兔',
//   '顺丰',
//   '其他',
// ];
const dv = new DataView();

const BrandsRate = ({
  branchId,
  dispatch,
  isParentFull,
  loading,
  title,
  screenToken,
  currentLevel,
  dispatchType,
}) => {
  const [pieData, setPieData] = useState([]);
  const [hasData, setHasData] = useState(false);
  const heightRef = useRef({});
  const [height, setHeight] = useState(0);
  const [firstBrand, setFirstBrand] = useState({ name: '', percent: '' });
  const brandIndex = useRef(1);
  const timer = useRef(null);

  const fetchData = useCallback(
    () => {
      dispatch({
        type: dispatchType,
        payload: {
          day: 1,
          cm_id: 'all',
          code: branchId,
          type: 'in',
          pageSize: 8,
          token: screenToken,
          level: currentLevel,
        },
      }).then((res = []) => {
        // const arr = [];
        // brandSort.forEach((brand, index) => {
        //   res.forEach(val => {
        //     if (val.brand.includes(brand)) {
        //       arr[index] = val;
        //     }
        //   });
        // });
        const sortArr = res.filter(i => i);
        dv.source(sortArr).transform({
          type: 'percent',
          field: 'num',
          dimension: 'brand',
          as: 'percent',
        });
        setHasData(sortArr.length > 0);
        const { rows = [] } = dv;
        const { brand, percent } = rows[0] || {};
        setFirstBrand({
          name: brand || '',
          percent: percent ? `${Math.round(percent * 1000) / 10}%` : '',
        });
        setPieData(dv);
      });
    },
    [branchId, dispatch, dispatchType],
  );

  useInterval(() => {
    const { rows = [] } = pieData;
    const { length } = rows;
    if (brandIndex.current >= length) {
      brandIndex.current = 0;
      return;
    }
    const { brand, percent } = rows[brandIndex.current] || {};
    setFirstBrand({
      name: brand || '',
      percent: percent ? `${Math.round(percent * 1000) / 10}%` : '',
    });
    brandIndex.current += 1;
  }, 3000);

  useEffect(
    () => {
      timer.current = setTimeout(() => {
        heightRef.current && setHeight(heightRef.current.clientHeight);
      }, 1000);
      return () => {
        timer.current && clearTimeout(timer.current);
      };
    },
    [isParentFull],
  );

  useUpdateEffect(fetchData, [fetchData]);
  useInterval(fetchData, 1000 * 60 * 60);

  return (
    <CommonBorder title={title} loading={loading}>
      <div style={{ height: '100%' }} ref={heightRef}>
        {hasData ? (
          <Chart
            className={styles.chart}
            style={{ backgroundColor: 'rgba(15, 24, 55, 0.7)' }}
            height={height}
            data={pieData}
            forceFit
            scale={cols}
            padding={['auto', 'auto', 'auto', 'auto']}
          >
            <Legend
              clickable={false}
              position="right-center"
              marker="square"
              textStyle={{
                fill: gradualTextColumn,
                fontSize: 20,
              }}
              name="brand"
              itemFormatter={text => text}
            />
            <Coord type="theta" innerRadius={0.65} radius={0.75} />
            <Axis name="percent" />
            <Tooltip
              showTitle={false}
              itemTpl="<li><span style=&quot;background-color:{color};&quot; class=&quot;g2-tooltip-marker&quot;></span>{name}: {value}</li>"
            />
            <Geom
              type="intervalStack"
              position="percent"
              color="brand"
              tooltip={[
                'brand*percent',
                (brand, percent) => {
                  percent = `${Math.round(percent * 1000) / 10}%`;
                  return {
                    name: brand,
                    value: percent,
                  };
                },
              ]}
              style={{
                lineWidth: 0,
                stroke: '#fff',
              }}
            />
            <Guide>
              <Guide.Text
                top
                position={['50%', '50%']}
                content={`${firstBrand.percent}`}
                style={{ textAlign: 'center', fontSize: 20, fill: gradualTextColumn }}
                offsetY={-12}
              />
              <Guide.Text
                top
                position={['50%', '50%']}
                content={`${firstBrand.name}`}
                style={{ textAlign: 'center', fontSize: 20, fill: gradualTextColumn }}
                offsetY={12}
              />
            </Guide>
          </Chart>
        ) : (
          <NoDate title="暂无数据" style={{ height }} />
        )}
      </div>
    </CommonBorder>
  );
};

export default connect(({ chartData, loading, global }, { dispatchType }) => ({
  screenToken: global.screenToken,
  branchId: chartData.currentAreaInfo.branchId,
  currentLevel: chartData.currentAreaInfo.currentLevel,
  loading: loading.effects[dispatchType],
}))(React.memo(BrandsRate));
